#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from models import Host
from common import try_int
from app03 import html_helper
# Create your views here.
# 操作数据库，生成分页
def index(request,page):

    """
    第一版
    count = Host.objects.all().count()
    result = Host.objects.all()
    ret = {'data':result,'count':count}
    return render_to_response('app03/index.html',ret)
    #####
    第二版
    count = Host.objects.all()[0:5].count()
    result = Host.objects.all()[0:5]
    ret = {'data':result,'count':count}
    return render_to_response('app03/index.html',ret)

    #print page
    # 第一页：0-5  page=1 (page-1)*5 - page*5
    # 第二页:5-10  page=2 (page-1)*5 - page*5  ...

    # 加入匹配的不是数字是处理
    try:
        page = int(page)
    except Exception,e:
        page = 1
    """
    # 获取cookie
    # print request.COOKIES

    per_item = try_int(request.COOKIES.get('pager_num',10),10)  # 获取cookie，如果没有默认是10
    page = try_int(page,1)
    count = Host.objects.all().count()
    #计算起始位置---封装到一个类中
    pageObj = html_helper.PageInfo(page,count,per_item)

    #result = Host.objects.all()[pageObj.start():pageObj.end()]
    result = Host.objects.all()[pageObj.start:pageObj.end]
    #从数据库中取数据
    page_string = html_helper.Pager(page,pageObj.all_page_count)
    '''
    page_html=[]
    first_html = "<a href='/app03/index/%d'>首页</a>" %(1,)
    page_html.append(first_html)
    if page <=1:
        prev_html = "<a href='#'>上一页</a>"
    else:
        prev_html = "<a href='/app03/index/%d'>上一页</a>" %(page-1,)
    page_html.append(prev_html)

    for i in range(all_page_count):
        if page == i+1:
            #a_html = "<a style='color:red';href='/app03/index/%d'>%d</a>" %(i+1,i+1)    # 加红显示当前页
            a_html = "<a class='selected';href='/app03/index/%d'>%d</a>" %(i+1,i+1) # 应用样式
        else:
            a_html = "<a href='/app03/index/%d'>%d</a>" %(i+1,i+1)

        page_html.append(a_html)
    if page < all_page_count:
        next_html = "<a href='/app03/index/%d'>下一页</a>" %(page+1,)
    else:
        next_html= "<a href='#'>下一页</a>"
    page_html.append(next_html)
    end_html = "<a href='/app03/index/%d'>尾页</a>" %(all_page_count,)
    page_html.append(end_html)


    page = mark_safe(''.join(page_html))  #将html标签 拼接后渲染到后。
        # 生成分页的html代码可以写入到单独模块中--封装
   '''
    ret = {'data':result,'count':count,'page':page_string}
   #return render_to_response('app03/index.html',ret)
    response = render_to_response('app03/index.html',ret)
    # 对客户端浏览器设置cookie
    #response.set_cookie('k1','v1')
    response.set_cookie('pager_num',per_item)
    return response

# 分割代码，精简后的代码，html_helper模块中的PageInfo类和Pager方法就可以重用。
# 通过ajax 修改为无刷新跳转。